<template>
  <el-dialog v-if="load" :close-on-click-modal="false" :title="form.arc_id ? '编辑' : '添加'" v-model="visible" align-center :z-index="2000" width="900px" @close="handleClose">
    <el-form ref="formRef" :model="form" label-position="top" :validate-on-rule-change="false" :label-width="140">
      <div class="grid grid-cols-2 gap-x-3">
        <div class="grid grid-cols-6 gap-x-3">
          <el-form-item label="规则名称" prop="audit_name" :rules="[{ required: true, message: '不能为空', trigger: 'blur' }]" class="col-span-5">
            <el-input v-model="form.audit_name" placeholder="规则名称" />
          </el-form-item>
          <el-form-item label="状态" prop="status" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
            <el-switch v-model="form.status" :active-value="1" :inactive-value="2" inline-prompt active-text="启用" inactive-text="禁用" />
          </el-form-item>
        </div>
        <el-form-item label="所属部门" prop="department_id" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
          <VCascader v-model="form.department_id" placeholder="部门" type="1" multiple collapse-tags filterable clearable checkStrictly class="w-full" />
        </el-form-item>
        <el-form-item label="审核界面" prop="audit_page" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
          <VSelect v-model="form.audit_page" placeholder="请选择" :options="options.audit_page" filterable clearable class="w-full" @change="form.doc_type = null" />
        </el-form-item>
        <el-form-item label="单据类型" prop="doc_type" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
          <VSelect v-model="form.doc_type" placeholder="请选择" :options="pageOptions" filterable clearable class="w-full" />
        </el-form-item>
        <el-form-item label="审核类型" prop="audit_type" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]" @change="auditTypeChange">
          <el-radio-group v-model="form.audit_type">
            <el-radio v-for="(d, i) in options.audit_type" :key="i" :value="d.value">{{ d.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </div>
      <div v-if="form?.audit_content?.length > 1" class="mb-[8px] font-semibold">审核条件</div>
      <div :class="form?.audit_content?.length > 1 ? 'bg-[#fafafa] px-[8px] rounded-8' : ''">
        <el-form-item v-for="(da, idx) in form.audit_content" :key="idx" :label="auditTypes[idx]" prop="audit_content"
          :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
          <div>
            <div class="flex items-center gap-x-3">
              <VSelect v-model="da.audit_role_id" placeholder="请选择" type="role" class="w-60" @change="({ option }) => (da.audit_role_name = option.label)" />
              <el-checkbox v-model="da.is_amount" :true-value="2" :false-value="1" @change="val => amountChange(val, da)">金额判断条件</el-checkbox>
              <template v-if="form.audit_type === 2">
                <el-button v-if="idx" type="primary" link @click="removeAutit(idx)">移除</el-button>
                <el-button v-else type="primary" link @click="addAutit">添加</el-button>
              </template>
            </div>
            <div class="flex items-center mt-2 gap-x-3" v-if="da.is_amount === 2">
              <div class="whitespace-nowrap">金额判断:</div>
              <VSelect v-model="da.amount_type" placeholder="请选择" :options="options.amount_type" clearable class="w-60" />
              <VGroup style="flex: 0 0 200px">
                <el-select v-model="da.amount_left_sign" style="flex: 0 0 80px" clearable placeholder="请选择">
                  <el-option v-for="(d, i) in [{ value: '>' }, { value: '>=' }]" :key="i" :value="d.value"></el-option>
                </el-select>
                <el-input-number v-model="da.amount_left" controls-position="right" :min="0" :step="0.01" :precision="2" style="flex: 0 0 120px" />
              </VGroup>
              <VGroup style="flex: 0 0 200px">
                <el-select v-model="da.amount_right_sign" style="flex: 0 0 80px" clearable placeholder="请选择">
                  <el-option v-for="(d, i) in [{ value: '<' }, { value: '<=' }]" :key="i" :value="d.value"></el-option>
                </el-select>
                <el-input-number v-model="da.amount_right" controls-position="right" :min="0" :step="0.01" :precision="2" style="flex: 0 0 120px" />
              </VGroup>
            </div>
          </div>
        </el-form-item>
      </div>
    </el-form>
    <template #footer>
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" :loading="loadings.create" @click="create(formRef)">确 定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { reactive } from 'vue';
import api from '../api'
import { ElMessage } from 'element-plus'
const props = defineProps({
  options: { type: Object, default: () => ({}) },
})
const emit = defineEmits(['close', 'success'])

const load = ref(false)
const visible = ref(false)
let loadings = reactive({})
const auditTypes = ['一级审核', '二级审核', '三级审核', '四级审核', '五级审核', '六级审核', '七级审核',]

// 表单处理
const formRef = ref()
const form = ref({})

// 审核界面变化
// 审核界面选项对应单据类型：
// 审核采购单：1、线上（对应采购单下单方式为1688下单及淘宝下单）、2、线下（对应采购单下单方式为线下）
// 付款申请审核：1、网络在线付款；2、阿里账期付款；3、转账付款；4、现金付款
// 异常冲账审核：无
const pages = {
  4: () => props.options.doc_type.filter(d => [4, 5, 9].includes(d.value)),
  5: () => props.options.doc_type.filter(d => [4, 6, 7, 8].includes(d.value)),
  7: () => props.options.doc_type.filter(d => [1].includes(d.value)),
  10: () => props.options.doc_type.filter(d => [2,3].includes(d.value)),
}
const pageOptions = computed(() => {
  const opts = pages[form.value.audit_page]
  return opts ? opts() : []
})

// 审核类型变化
const auditTypeChange = () => {
  form.value.audit_content = [
    {
      audit_role_id: undefined,
      amount_type: 1,
      is_amount: 1,
      amount_left_sign: '>=',
      amount_left: undefined,
      amount_right_sign: '<=',
      amount_right: undefined
    }
  ]
}

// 金额判断条件变化
const amountChange = (val, da) => {
  val === 2 && Object.assign(da, {
    amount_type: 1,
    amount_left_sign: '>=',
    amount_left: 0,
    amount_right_sign: '<=',
    amount_right: 0
  })
}

// 添加审核等级
const addAutit = () => {
  if (form.value.audit_content.length > 6) {
    ElMessage.error('最多添加七级审核')
    return
  }
  form.value.audit_content.push({
    audit_role_id: undefined,
    amount_type: 1,
    is_amount: 1,
    amount_left_sign: '>=',
    amount_left: undefined,
    amount_right_sign: '<=',
    amount_right: undefined
  })
}
// 移除审核等级
const removeAutit = (idx) => {
  form.value.audit_content.splice(idx, 1)
}

// 打开弹窗
const open = async (id) => {
  form.value = {}
  if (!load.value) {
    load.value = true
    await 1
  }
  form.value = {
    audit_name: '',
    audit_page: '',
    doc_type: '',
    audit_type: 1,
    status: 1,
    audit_content: '',
    audit_content: [
      {
        audit_role_id: undefined,
        amount_type: 1,
        is_amount: 1,
        amount_left_sign: '>=',
        amount_left: undefined,
        amount_right_sign: '<=',
        amount_right: undefined
      }
    ]
  }

  loadings = reactive({})
  visible.value = true
  formRef?.value?.resetFields()
  // 编辑
  if (id) {
    const res = await api.detail({ arc_id: id })
    form.value = res.data
  }
}
// 关闭弹窗
const close = () => {
  visible.value = false
}

const handleClose = () => {
  emit('close')
}
// 提交
const create = async (formRef) => {
  const validator = await formRef.validate()
  if (!validator) return
  loadings.create = true
  form.value.audit_content = form.value.audit_content.map((da, idx) => {
    da.audit_level = idx + 1
    // da.audit_role_name = roleOptions.value.find(d => d.value === da.audit_role_id)?.label
    return da
  })
  api[form.value.arc_id ? 'edit' : 'create'](form.value).then(res => {
    ElMessage.success('保存成功')
    emit('success')
    close()
  }).finally(() => {
    loadings.create = false
  })
}

defineExpose({ open })
</script>